package com.chixing.service.impl;

import com.alibaba.fastjson.JSON;
import com.chixing.mapper.CustomerMapper;
import com.chixing.mapper.EvaluateMapper;
import com.chixing.mapper.PraisedMapper;
import com.chixing.mapper.ReplyMapper;
import com.chixing.pojo.*;
import com.chixing.service.EvaluateService;
import com.chixing.util.DateUtil;
import com.chixing.util.ServerResponse;
import com.chixing.util.redis.LikedStatusEnum;
import com.chixing.util.redis.RedisKeyUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;

@Component
@Service
public class EvaluateServiceImpl implements EvaluateService {
    @Autowired
    private EvaluateMapper evaluateMapper;

    @Autowired
    private ReplyMapper replyMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private PraisedMapper praisedMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

     //  根据汽车id  分页查询评论 用户信息 和 评论信息 和 回复者信息及回复的内容
    @Override
    public ServerResponse getEvaluateByCarId(Integer carId,Integer pageNum) {

        Sort sort = Sort.by(Sort.Direction.DESC, "DEVID").and(Sort.by(Sort.Direction.DESC,"evaluate_time"));//多条件DEVID、time
        Query query=new Query(Criteria.where("carId").is(carId));
        System.out.println(query);
        List<Evaluate> evaluateList = mongoTemplate.find(query.with(sort).limit(1000),Evaluate.class);
        Page<Evaluate> page = PageHelper.startPage(pageNum,5);                // 分页
        PageInfo pageInfo = page.toPageInfo();


        List<EvaluateCustomerReplyVO> evaluateCustomerReplyVOList = new ArrayList<>();
        List<ReplyCustomerVO> replyCustomerVOList;
        for(Evaluate evaluate : evaluateList){
            Query query1=new Query(Criteria.where("evaluateId").is(evaluate.getEvaluateId()).and("status").is(0));
            String redisEvaluatePraisedKey = evaluate.getEvaluateId().toString();
            if(redisTemplate.opsForHash().hasKey(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,redisEvaluatePraisedKey)){
                String count = redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,redisEvaluatePraisedKey).toString();
                evaluate.setEvaluatePraisedCount(Integer.valueOf(count));
            }
            List<Reply> replyList=mongoTemplate.find(query1,Reply.class);
            System.out.println("回复为:"+replyList);
           /* ReplyExample replyExample = new ReplyExample();
            replyExample.createCriteria().andEvaluateIdEqualTo(evaluate.getEvaluateId()).andStatusEqualTo(0);
            List<Reply> replyList = replyMapper.selectByExample(replyExample);      //通过评价id查询所有回复评价的评论*/
            replyCustomerVOList = new ArrayList<>();          // 用来接收所有回复评价的评论
            Customer customer = customerMapper.selectByPrimaryKey(evaluate.getCustId()); // 查询评价用户
            if(replyList.size()!=0) {
                for (Reply reply : replyList) {
                    System.out.println(reply);
                    Customer replyCustomer = customerMapper.selectByPrimaryKey(reply.getCustId()); //查询所有的回复用户
                    replyCustomerVOList.add(new ReplyCustomerVO(replyCustomer, reply));  // 将所有的回复用户和回复一个VO集合中
                }
            }
            evaluateCustomerReplyVOList.add(new EvaluateCustomerReplyVO(evaluate,customer, replyCustomerVOList)); // 将当前评价用户及评价信息，以及回复者和回复信息封
        }
        pageInfo.setList(evaluateCustomerReplyVOList);
        if(evaluateCustomerReplyVOList.size() != 0)
            return ServerResponse.getSuccess(pageInfo);
        return ServerResponse.getFail(null);
    }
//点赞操作
    @Override
    public ServerResponse updateEvaluateByCarId(Integer evaluateId, Integer custId, Integer status) {
        //获取MongoDB数据库评论ID对应的评论
        Query query=new Query(Criteria.where("evaluateId").is(evaluateId));
        int count ;

        if(redisTemplate.opsForHash().hasKey(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,evaluateId.toString())){
            count = Integer.valueOf(redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,evaluateId.toString()).toString());
        }else {
            Evaluate evaluate = mongoTemplate.findOne(query, Evaluate.class);
            Praised praised = new Praised();
            praised.setEvaluateId(evaluateId);
            praised.setCustId(custId);
            praised.setStatus(status);
            System.out.println(evaluate);
            System.out.println(evaluate);
            count = evaluate.getEvaluatePraisedCount();
            redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,evaluateId.toString(),String.valueOf(count));
        }

            /*String praisedString = JSON.toJSONString(praised);
            // 从hash中拿出来这个字符串
            Praised praised1 = JSON.parseObject(praisedString,Praised.class);*/

        if(status == 0) {//0为有效
            redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,evaluateId.toString(),1);


            String key = RedisKeyUtils.getLikedKey(evaluateId, custId);
            String value = LikedStatusEnum.LIKE.getCode().toString() + "::" + DateUtil.dateToString(new Date(),DateUtil.DATE_PATTEN_YMDHMS);
            redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, value);
            count++;

        }else if(status==1){
            redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT,evaluateId.toString(),-1);

            String key=RedisKeyUtils.getLikedKey(evaluateId,custId);
            String value = LikedStatusEnum.UNLIKE.getCode().toString() + "::" + DateUtil.dateToString(new Date(),DateUtil.DATE_PATTEN_YMDHMS);
            redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED,key,value);
            count--;
        }

        return ServerResponse.updateSuccess(count);
    }

    @Override
    public ServerResponse getEvaluatePraisedStatus(Integer evaluateId, Integer custId) {


        Praised praised = null;
        System.out.println("custId:"+custId);

        System.out.println("evaluateId:"+evaluateId);
        String praisedHashKey = evaluateId + "::" + custId;
        System.out.println(praisedHashKey);
        System.out.println(redisTemplate.opsForHash().hasKey(RedisKeyUtils.MAP_KEY_USER_LIKED,praisedHashKey));
        if(redisTemplate.opsForHash().hasKey(RedisKeyUtils.MAP_KEY_USER_LIKED,praisedHashKey)){
            String stringValue = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED,praisedHashKey);
            System.out.println("stringValue"+stringValue);
            String [] valueStrings = stringValue.split("::");

            praised = new Praised();
            for(String s : valueStrings){
                System.out.println(s);
            }

            praised.setEvaluateId(evaluateId);
            praised.setCustId(custId);
            praised.setPrisedTime(DateUtil.stringToDate(valueStrings[1],DateUtil.DATE_PATTEN_YMDHMS));
            praised.setStatus(Integer.valueOf(valueStrings[0]));
        }else {
            Praised praisedExm = new Praised();
            praisedExm.setEvaluateId(evaluateId);
            praisedExm.setCustId(custId);
            Query query = new Query(Criteria.byExample(praisedExm));
            praised = mongoTemplate.findOne(query, Praised.class);

        }
        if(praised != null)
            return ServerResponse.getSuccess(praised);
        return ServerResponse.getFail(null);

    }
    //获取点赞状态操作

}


